<template>
  <view v-if="loginFlag && isTrustClass" class="ws-classroom" :style="{ paddingTop: `${totalNavigationHeight * 2}rpx` }">
    <NavigationBar navigation-title="五商课堂" />

    <view class="ws-top">
      <view v-for="(item, index) in wsList" :key="item.text" class="top-item">
        <text class="item-num">
          {{ detailData?.[item.prop] }}
        </text>
        <view class="item-content">
          <image class="item-ping" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/pingzi.png" />
          <view class="item-bg" :class="`item-bg-${index + 1}`" :style="{ height: `${168 / (detailData?.[item.totalProp] || 1) * (detailData?.[item.prop] || 0)}rpx` }" />
          <image class="item-ping" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/pingzi_bg.png" />
          <text class="item-text">
            {{ item.text }}
          </text>
        </view>
      </view>
    </view>

    <view class="ws-content">
      <image class="ws-line line-left" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/line_left.png" />
      <image class="ws-line line-right" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/line_right.png" />
      <view class="calendar">
        <!-- 月份切换 -->
        <view class="calendar-header">
          <image class="calendar-btn" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/icon_left.png" @click="prevMonth" />
          <text class="calendar-date">
            {{ `${year}年${month + 1}月` }}
          </text>
          <image class="calendar-btn" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/icon_right.png" @click="nextMonth" />
        </view>

        <view class="calendar-tab">
          <text v-for="(week, index) in detailData?.fiveWisdomItems" :key="week.week" class="week" :class="(index + 1) === chooseWeek?.weekIndex ? 'choose-week' : ''" @click="handleChoose(week)">
            第{{ ['一', '二', '三', '四', '五', '六'][week.week - 1] }}周
          </text>
        </view>

        <view v-if="chooseWeek?.week?.[0]?.length" class="calendar-body">
          <view v-for="(line, row) in chooseWeek?.week" :key="`line${row}`" class="week-line">
            <image class="line-img" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/week_line.png" />
            <template v-for="(day, li) in line" :key="day.data.detailId">
              <view class="day" :class="`day_${day.data.wisdomType}_${li + 1}_1`">
                <image class="day-img" :src="`https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250519/week_${day.data.wisdomType}_${li + 1}_1.png`" />
                <view class="day-content">
                  <text class="day-text">
                    周{{ day.weekText }}
                  </text>
                  <view class="day-wraper">
                    <view class="day-box" @click="handleDayClick(day.data)">
                      <view class="day-main">
                        <image class="day-main-img" :src="`https://shuyutk.oss-cn-qingdao.aliyuncs.com${day.data.coverPic}`" mode="aspectFill" />
                        <text class="day-main-process" :class="day.data.progress === 100 ? 'process-end' : ''">
                          {{ day.data.progress === 100 ? '已完成' : `${day.data.progress}%` }}
                        </text>
                      </view>
                      <text class="day-title">
                        {{ day.data.title }}
                      </text>
                    </view>
                  </view>
                </view>
              </view>
            </template>
          </view>
        </view>
        <view v-else class="no-data">
          暂无内容~
        </view>
      </view>
    </view>
  </view>

  <template v-else-if="!loginFlag || (isTrustClass === 0)">
    <NavigationBar navigation-title="五商课堂" />
    <NoDataPage :status="!loginFlag ? 1 : 2" :type="2" :info-text="!loginFlag ? '暂未登录，立即登录开启托管日程吧' : '暂无托管内容'" :btn-text="!loginFlag ? '登录' : '联系老师报名吧'" />
  </template>
</template>

<script setup lang="ts">
import { getFiveWisdomList, getUserTrustClass } from '@/api/wsClassroom/index';
import type { FiveWisdomItem, GetFiveWisdomListParams, GetFiveWisdomListResult } from '@/api/wsClassroom/type';
import { getFirstDayOfMonth } from '@/utils/common/index';
import { getNavigationHeight } from '@/utils/auth/index';
import { useUserStore } from '@/store';
import { isLogin } from '@/utils/auth';

const userStore = useUserStore();
const totalNavigationHeight = ref(getNavigationHeight());

const loginFlag = ref<boolean>(isLogin());

const wsList = ref<Array<{ text: string; prop: string; totalProp: string }>>([
  {
    text: '智商',
    prop: 'hasIqNum',
    totalProp: 'iqNum',
  },
  {
    text: '情商',
    prop: 'hasEqNum',
    totalProp: 'eqNum',
  },
  {
    text: '财商',
    prop: 'hasFqNum',
    totalProp: 'fqNum',
  },
  {
    text: '逆商',
    prop: 'hasAqNum',
    totalProp: 'aqNum',
  },
  {
    text: '语商',
    prop: 'hasLqNum',
    totalProp: 'lqNum',
  },
]);

const pageParams: GetFiveWisdomListParams = {
  pageNum: 1,
  pageSize: 10,
  month: getFirstDayOfMonth(),
};
const detailData = ref<GetFiveWisdomListResult>();
const year = ref<number>(new Date().getFullYear());
const month = ref<number>(new Date().getMonth()); // 0-based
const chooseWeek = ref<{ weekIndex: number; week: { weekText: string; data: FiveWisdomItem }[][] }>();
const handleChoose = (week: { week: number; detailList: Array<FiveWisdomItem> }) => {
  // const dataList = detailData.value!.fiveWisdomItems.find(item => item.week === weekIndex)?.detailList;
  const textList = ['一', '二', '三', '四', '五', '六', '日'];
  const dataList = week.detailList;
  const weekList = [];
  let weekItem = [];
  let num = 0;
  for (let i = 0; i < dataList.length; i++) {
    num += 1;
    if (num > 3) {
      num = 1;
      weekList.push(weekItem);
      weekItem = [];
    }
    weekItem.push({
      weekText: textList[dataList[i].dayOfWeek - 1],
      data: dataList[i],
    });
  }
  weekList.push(weekItem);
  chooseWeek.value = {
    weekIndex: week.week,
    week: weekList,
  };
};
// 获取当前月每周的日期
// const weeks = computed(() => {
//   const weekText = ['一', '二', '三', '四', '五', '六', '日'];
//   const result: ({ date: number; weekText: string; weekIndex: number })[][] = [];
//   const currentDate = new Date(year.value, month.value, 1);
//   const currentWeekStart = new Date(currentDate);

//   // 找到第一个周一之前的日期
//   while (currentWeekStart.getDay() !== 1) {
//     currentWeekStart.setDate(currentWeekStart.getDate() - 1);
//   }

//   // 遍历整个月份，按周划分
//   while (
//     (currentWeekStart.getMonth() <= month.value && currentWeekStart.getFullYear() === year.value)
//     || (currentWeekStart.getFullYear() === year.value - 1 && currentWeekStart.getMonth() === 11)
//   ) {
//     const week: ({ date: number; weekText: string; weekIndex: number })[] = [];
//     for (let i = 0; i < 7; i++) {
//       const day = new Date(currentWeekStart);
//       day.setDate(day.getDate() + i);
//       if (day.getMonth() === month.value && day.getFullYear() === year.value) {
//         week.push({
//           date: day.getDate(),
//           weekText: weekText[i],
//           weekIndex: i + 1,
//         });
//       }
//     }
//     result.push(week);
//     currentWeekStart.setDate(currentWeekStart.getDate() + 7);
//   }

//   return result;
// });
// 获取当日在当月中属于第几周
const getCurrentWeekIndex = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth(); // 0-based
  const currentDate = date.getDate();

  const firstDayOfMonth = new Date(year, month, 1);
  const firstDayOfWeek = firstDayOfMonth.getDay();

  const offset = (firstDayOfWeek === 0 ? 7 : firstDayOfWeek);

  return Math.ceil((currentDate + offset - 1) / 7);
};
const handleDayClick = (item: FiveWisdomItem) => {
  uni.navigateTo({
    url: `/pages/views/wsClassroom/detail?id=${item.detailId}&date=${pageParams.month.slice(0, 7)}`,
  });
};

const getData = (i?: number) => {
  chooseWeek.value = undefined;
  getFiveWisdomList(pageParams).then((res: GetFiveWisdomListResult) => {
    detailData.value = res;
    if (!detailData.value)
      return;

    if (i) {
      const weekItem = detailData.value.fiveWisdomItems.find(item => item.week === i);
      handleChoose(weekItem || detailData.value.fiveWisdomItems[0]);
      return;
    }
    const index = getCurrentWeekIndex();
    const weekItem = detailData.value.fiveWisdomItems.find(item => item.week === index);
    handleChoose(weekItem || detailData.value.fiveWisdomItems[0]);
  });
};

// 切换到上个月
const prevMonth = () => {
  if (month.value === 0) {
    month.value = 11;
    year.value--;
  }
  else {
    month.value--;
  }
  pageParams.month = `${year.value}-${(month.value + 1).toString().padStart(2, '0')}-01`;
  getData(month.value === new Date().getMonth() ? 0 : 1);
};
// 切换到下个月
const nextMonth = () => {
  if (month.value === 11) {
    month.value = 0;
    year.value++;
  }
  else {
    month.value++;
  }
  pageParams.month = `${year.value}-${(month.value + 1).toString().padStart(2, '0')}-01`;
  getData(month.value === new Date().getMonth() ? 0 : 1);
};

// 获取报名状态
const isTrustClass = ref<number | null>(null);
const getStatus = () => {
  getUserTrustClass().then((res) => {
    isTrustClass.value = res.flag;
    if (isTrustClass.value)
      getData();
  });
};

onLoad(() => {
  if (loginFlag.value) {
    getStatus();
  }
});

onShow(() => {
  if (loginFlag.value && isTrustClass.value)
    getData(chooseWeek.value ? chooseWeek.value.weekIndex : 0);
});

// 分享
uni.showShareMenu({
  withShareTicket: true,
  menus: ['shareAppMessage', 'shareTimeline'],
});
onShareAppMessage(() => {
  return {
    title: userStore.share_txt,
    imageUrl: userStore.share_pic_url,
  };
});
</script>

<style lang="scss" scoped>
.ws-classroom {
  position: relative;
  height: 100%;
  padding: 24rpx 40rpx 0;
  background: linear-gradient( 180deg, #FFF3E2 0%, #FFFFFF 100%);
  display: flex;
  flex-direction: column;

  .ws-top {
    display: flex;
    justify-content: space-between;
    padding: 50rpx 0;

    .top-item {
      width: 101rpx;
      display: flex;
      flex-direction: column;
      align-items: center;

      .item-num {
        height: 36rpx;
        padding-bottom: 2rpx;
        font-size: 24rpx;
        color: #87837B;
        line-height: 36rpx;
      }

      .item-content {
        position: relative;
        width: 101rpx;
        height: 178rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: flex-end;

        .item-ping {
          position: absolute;
          top: 0;
          left: 0;
          width: 101rpx;
          height: 178rpx;
        }

        .item-bg {
          position: absolute;
          left: 0;
          bottom: 0;
          width: 101rpx;
          clip-path: polygon(0% 0%, 50% 6rpx, 100% 0%, 100% 100%, 0% 100%);
        }

        .item-bg-1 {
          background: rgba(124, 195, 255, 0.4);
        }
        .item-bg-2 {
          background: rgba(251, 181, 22, 0.4);
        }
        .item-bg-3 {
          background: rgba(255, 77, 77, 0.4);
        }
        .item-bg-4 {
          background: rgba(44, 205, 151, 0.4);
        }
        .item-bg-5 {
          background: rgba(206, 154, 249, 0.4);
        }

        .item-text {
          position: relative;
          padding-bottom: 19rpx;
          font-size: 24rpx;
          color: #251504;
          line-height: 36rpx;
        }
      }
    }
  }

  .ws-content {
    position: relative;
    flex: 1;
    overflow: hidden;
    padding-top: 36rpx;
    display: flex;
    flex-direction: column;

    .ws-line {
      position: absolute;
      top: 0;
      width: 120rpx;
      height: 60rpx;
      z-index: 1;
    }
    .line-left {
      left: 111rpx;
    }
    .line-right {
      right: 111rpx;
    }

    .calendar {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding: 42rpx 32rpx 52rpx 32rpx;
      background: #fff;
      box-shadow: 0 17rpx 29rpx 0 rgba(183,175,154,0.24);
      border-radius: 32rpx;
      margin-bottom: 24rpx;
      overflow: auto;

      .calendar-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .calendar-btn {
          width: 32rpx;
          height: 32rpx;
          margin: 15rpx;
        }

        .calendar-date {
          font-size: 28rpx;
          color: #313131;
          line-height: 62rpx;
        }
      }

      .calendar-tab {
        padding-top: 38rpx;
        padding-bottom: 92rpx;
        display: flex;
        justify-content: space-between;

        .week {
          font-size: 28rpx;
          color: #87837B;
          line-height: 42rpx;
        }

        .choose-week {
          color: #31C966;
        }
      }

      .calendar-body {
        flex: 1;
        overflow: auto;

        .week-line {
          position: relative;
          height: 392rpx;

          .line-img {
            position: absolute;
            top: 0;
            left: 0;
            width: 606rpx;
            height: 52rpx;
          }

          .day {
            position: absolute;
            padding: 60rpx 24rpx 0 14rpx;

            .day-content {
              display: flex;
              flex-direction: column;
              align-items: center;
            }

            .day-img {
              position: absolute;
              top: 0;
              left: 0;
              width: 100%;
              height: 100%;
            }

            .day-text {
              position: relative;
              font-size: 20rpx;
              color: #87837B;
              line-height: 44rpx;
            }

            .day-wraper {
              width: 100%;
              display: flex;
              justify-content: space-between;

              .day-box {
                display: flex;
                flex-direction: column;
                align-items: center;
              }
            }

            .day-main {
              position: relative;
              width: 160rpx;
              height: 90rpx;
              border-radius: 8rpx;
              overflow: hidden;

              .day-main-img {
                position: absolute;
                top: 0;
                left: 0;
                width: 160rpx;
                height: 90rpx;
              }

              .day-main-process {
                position: absolute;
                bottom: 0;
                right: 0;
                padding: 0 8rpx;
                font-weight: bold;
                font-size: 18rpx;
                line-height: 30rpx;
                color: #FB7C00;
                background: #FFD184;
                border-radius: 8rpx 0 8rpx 0;
              }
              .process-end {
                background: #B2D233;
                color: #4A8EC7;
              }
            }

            .day-title {
              width: 160rpx;
              position: relative;
              font-size: 20rpx;
              line-height: 50rpx;
              color: #87837B;
              overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
              text-align: center;
            }
          }
          .day_1_1_1, .day_2_1_1, .day_3_1_1, .day_4_1_1, .day_5_1_1 {
            top: 17rpx;
            left: 0;
            width: 191rpx;
            height: 267rpx;

            .day-content {
              transform: rotate(4deg);
            }
          }
          .day_1_2_1, .day_2_2_1, .day_3_2_1, .day_4_2_1, .day_5_2_1 {
            top: 27rpx;
            left: 208rpx;
            width: 196rpx;
            height: 270rpx;

            .day-content {
              padding-left: 2rpx;
            }
          }
          .day_1_3_1, .day_2_3_1, .day_3_3_1, .day_4_3_1, .day_5_3_1 {
            top: 17rpx;
            right: 0;
            width: 200rpx;
            height: 275rpx;

            .day-content {
              transform: rotate(-7deg);
              padding-left: 7rpx;
            }
          }
          .day_1_1_2, .day_2_1_2, .day_3_1_2, .day_4_1_2, .day_5_1_2 {
            top: 29rpx;
            left: 0;
            width: 354rpx;
            height: 268rpx;
            padding-left: 12rpx;
            padding-right: 14rpx;

            .day-content {
              transform: rotate(2deg);
            }
          }
          .day_1_2_2, .day_2_2_2, .day_3_2_2, .day_4_2_2, .day_5_2_2 {
            top: 31rpx;
            right: 16rpx;
            width: 380rpx;
            height: 296rpx;

            .day-content {
              padding-left: 14rpx;
              padding-right: 2rpx;
              transform: rotate(-2deg);
            }
          }
        }
      }

      .no-data {
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        padding-top: 40rpx;
        padding-bottom: 80rpx;
        font-size: 32rpx;
        color: #888888;
        line-height: 48rpx;
      }
    }
  }
}
</style>
